<template>
	<!-- 任务列表 -->
	<view class="page">
		<uv-navbar title="检查记录" auto-back placeholder />
		<view class="list ss-r-20 ss-shadow">
			<view class="ss-grey-2 ss-w-100 ss-font-28">
				<view class="list_tit ss-flex ss-p-x-36 ss-p-y-26">
					<view class="des">检测项目</view>
					<view class="ss-m-x-20 ss-black ss-flex-1">{{ state.name || "-" }}</view>
				</view>
				<view class="ss-flex ss-p-x-36 ss-col-top ss-p-y-26 req">
					<view class="des">测试方法和要求</view>
					<view class="ss-m-x-20 ss-black ss-flex-1">
						{{ state.specification || "-" }}
					</view>
				</view>
			</view>
			<g-tabs-top :list="tabList" v-model:current="state.currentTab" sticky top="44px" keyName="name"
				:scroll="false" @change="changeTab" />
			<view class="ss-p-26 ss-bg-w ss-font-28" v-if="state.currentTab == 0">
				<view class="ss-flex ss-col-center ss-m-y-10">
					<view class="tabCard_l"></view>
					<view class="ss-m-x-10 ss-black">基本信息</view>
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 已检查数量 （不允许修改） </view>
					<uv-input placeholder="请输入内容" border="surround" v-model="state.completedCount" disabled />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"><text style="color: red;">
							*
						</text> 检查数量（应完成{{ state.allowTotal }} 剩余 {{ state.total - state.completedCount }}） </view>
					<uv-input placeholder="输入数量" border="surround" type="number" v-model="checkDetails.inspectCount" />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> <text v-if="checkDetails.status == 2" style="color: red;">
							*
						</text> 问题描述 </view>
					<g-select
						v-model:value="problemId"
						:list="problemList"
						key-value="id"
						key-name="problemContent"
						title="选择问题"
						placeholder="请选择问题"
						@change="changeProblem"
					/>
					<uv-textarea v-if="problemId == -1" v-model="checkDetails.problemDescription" placeholder="请填写问题描述" />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 位置描述 </view>
					<uv-input placeholder="请填写位置描述" border="surround" v-model="checkDetails.locationDescription" />
				</view>
				<view class="ss-flex ss-col-center ss-m-y-10">
					<view class="tabCard_l"></view>
					<view class="ss-m-x-10 ss-black">检查结果 (必填)</view>
				</view>
				<view class="ss-flex ss-col-center ss-m-y-10">
					<view>
						<uv-radio-group>
							<uv-radio :customStyle="{
                  border:
                    checkDetails.status == item.id
                      ? '2px soild #4EA770'
                      : '2px soild #DCDFE6',
                }" v-for="(item, index) in resList" :key="index" :label="item.name" :name="item.name"
								@change="changeRadio(item.id)" activeColor="#4EA770">
							</uv-radio>
						</uv-radio-group>
					</view>
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 备注 </view>
					<uv-textarea v-model="checkDetails.remark" />
				</view>
				<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
					<view class="ss-m-y-16"> 上传照片 </view>
					<Task-upload v-model:value="state.imgUrl" time-mark multiple :max="9" address-mark
						@state="upLoadState" />
				</view>
				<view class="btn-box">
					<uv-button
						text="提交"
						type="primary"
						shape="circle"
						color="#4EA770"
						:throttle-time="1000"
						:custom-style="{width: '100%'}"
						@click="handleSubmit"
					/>
				</view>
			</view>
			<view v-if="state.currentTab == 1" class="ss-bg-w">
				<g-steps :steps="dataList" direction="column" slot-class=".step-remark" :current="4" stepsId="checkId"
					key-name="day">
					<template v-for="(i, k) in dataList" :key="k" #[i.slot]="{ scope }">
						<view class="step-remark">
							<view class="step-row ss-col-center">
								<view class="step-row-left">
									<view class="ss-flex ss-flex-1">
										<view class="operator">{{ scope.inspectUserNickName || "-" }}</view>
										<view class="post-tag">
											{{ enumUserType(scope.inspectUserType) }}
										</view>
									</view>
									<view class="ss-m-y-14"> 检查数量：{{ scope.inspectCount }} </view>
								</view>
								<uv-avatar :src="scope.inspectUserAvatar" size="106rpx"
									:customStyle="{ padding: '20rpx', paddingBottom: '0' }" />
							</view>
							<view class="step-bottom">
								<uv-text :text="`检查结果：${scope.status == '1' ? '合格' : '不合格'}`" color="#757575"
									size="24rpx" margin="10rpx 0" />
								<uv-text :text="scope.createTime" color="#757575" size="24rpx" />
							</view>
						</view>
					</template>
				</g-steps>
				<view class="more ss-p-y-10 ss-font-28 ss-grey-2" v-if="dataList.length != 0" @click="goMore">
					{{ state.isText }}
				</view>
				<uv-empty v-if="dataList.length === 0" :customStyle="{ padding: '10vh 0' }" :icon="empty" text="暂无记录" />

			</view>
			<view v-if="state.currentTab == 2" class="ss-bg-w ss-p-30" style="text-align: center">
				<view class="tabBox" v-if="videoName.length!=0">
					<uv-scroll-list :indicator="false">
						<view class="ss-flex">
							<view class="tab_list ss-font-28 ss-p-16" v-for="(i,index) in videoName" :key="index"
								:style="{color:state.currentVideo == index?'#fff':'#000',background:state.currentVideo == index?'#4EA770':'#fff'}"
								@click="changeVideo(index)">
								<view>
									{{i}}
								</view>
							</view>
						</view>
					</uv-scroll-list>
				</view>
				<video :src="webSrc(videoList[state.currentVideo])" v-if="videoList.length!=0" />
				<uv-empty v-if="videoList.length == 0" margin-top="2vh" :icon="empty" :text="`暂无视频`" />
				<view class="videoGuidanceSty"> {{ checkDetails.videoGuidance || "-" }} </view>
			</view>
		</view>

		<view class="add-icon ss-bg-w ss-flex ss-row-center ss-font-26" @click="Jump" :style="{
			right: isCollapse ? '-104rpx' : 0,
		}">
			<uv-icon :name="iconCreate" size="26rpx" label="新建工单" label-size="24rpx"
				:label-color="isCollapse ? 'transparent' : '#212121'" />
		</view>
	</view>
	<vv-dialog v-model:projectType="state.projectType" :count="state.total - state.completedCount" :type="state.type" />
</template>
<script setup>
	import {
		reactive,
		ref
	} from "vue";
	import {
		onLoad,
		onBackPress,
		onPageScroll
	} from "@dcloudio/uni-app";
	import {
		deviceDetail,
		deviceItem,
		recordAdd,
		recordList,
		getProblemData
	} from "@/request/task.js";
	import {
		webSrc,
		timeFormat,
		enumUserType
	} from "@/common/mothed.js";
	import TaskUpload from "@/pages/Task/cp/TaskUpload.vue"
	import vvDialog from "@/components/Dialog/Dialog.vue"
	import iconCreate from "@/static/order/icon_create.png";
	import empty from "@/static/empty.png";

	const checkDetails = ref({
		inspectCount: 0,
		problemDescription: "",
		locationDescription: "",
		remark: "",
		status: "",
		imgUrl: "",
		videoGuidance: ""
	});
	const isCollapse = ref(false); // 是否折叠按钮
	const total = ref(0); // 总条数
	const queryParams = ref({
		deviceTasksItemId: "",
		pageNum: 1, // 页数
		pageSize: 10, // 条数
	});
	const tabList = ref([{
		id: 0,
		name: "任务填报"
	}, {
		id: 1,
		name: "检查记录"
	}, {
		id: 2,
		name: "视频指导"
	}]);

	const resList = ref([{
			id: 1,
			name: "合格"
		},
		{
			id: 2,
			name: "不合格"
		},
	]);
	const unBack = ref(false); // 阻止放行
	const disabled = ref(false); // 禁止提交

	const videoList = ref([]);
	const videoName = ref([]);
	const dataList = ref([]);
	const problemList = ref([]); // 问题列表
	const problemId = ref(); // 临时问题id

	const state = reactive({
		currentVideo: 0,
		id: "",
		currentTab: 0,
		completedCount: 0,
		type: "MONTH", // 检查项周期类型
		taskItemId: "",
		specification: "",
		name: "",
		isText: "",
		imgUrl: [],
		projectType: 0,
		isFinish: false,
		total: 0,
		allowTotal: 0,
		systemId: '',
		deviceId: '',
	});

	onLoad((e) => {
		queryParams.value.deviceTasksItemId = e.taskItemId;
		checkDetails.value.deviceTasksItemId = e.taskItemId;
		state.deviceId = e.deviceId;
		state.id = e.id;
		state.systemId = e.systemId;
		state.completedCount = parseInt(e.completedCount) || 0;
		state.type = e.type;
		state.total = parseInt(e.total) || 0;
		state.allowTotal = parseInt(e.allowTotal) || 0;
		getDetails();
		getProblems();
	});

	onPageScroll((e) => {
		isCollapse.value = e.scrollTop > 80;
	});

	onBackPress((e) => {
		if (unBack.value) {
			uni.showModal({
				title: "退出确认",
				content: "有文件尚未提交成功，是否取消？",
				showCancel: true,
				confirmColor: "#4EA770",
				success: ({
					confirm
				}) => {
					if (confirm) {
						unBack.value = false;
						uni.navigateBack();
					}
				},
			});
		}
		return unBack.value; //阻止返回
	});

	// 监听上传状态
	const upLoadState = (val) => {
		unBack.value = val.noBack;
		console.log('上传动态：', val);
		disabled.value = val.state != 'success';
	}

	// 提交检查记录
	const handleSubmit = () => {
		if (checkDetails.value.inspectCount == "" || checkDetails.value.inspectCount == 0) {
			uni.showToast({
				title: "请填写检查数量",
				icon: "none",
			});
			return;
		}
		if (state.completedCount + parseInt(checkDetails.value.inspectCount || '0') > state.total) {
			state.projectType = 4
			return;
		}
		if (checkDetails.value.status == "") {
			uni.showToast({
				title: "请选择检查结果",
				icon: "none",
			});
			return;
		}
		if (checkDetails.value.status == 2 && checkDetails.value.problemDescription == "") {
			uni.showToast({
				title: "请输入问题描述",
				icon: "none",
			});
			return;
		}
		if (state.imgUrl.length == 0) {
			uni.showToast({
				title: "请上传检查照片",
				icon: "none",
			});
			return;
		}
		if (disabled.value) {
			uni.showToast({
				title: "请照片上传完成再提交",
				icon: "none",
			});
			return;
		}
		checkDetails.value.imgUrl = state.imgUrl.join(",");
		recordAdd(checkDetails.value).then((res) => {
			if (res.code == 200) {
				//任务选择刷新
				uni.$emit("listSelectStateTask");
				state.isFinish = res.data.isFinish
				problemId.value = null;
				if (state.isFinish) {
					state.projectType = 3
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none",
					});
				}
				resetForm();
				unBack.value = false;
				state.currentTab = 1;
				changeTab({
					id: 1
				})
			}
		});
	};

	// 重置表单
	const resetForm = () => {
		checkDetails.value.inspectCount = 0;
		checkDetails.value.problemDescription = "";
		checkDetails.value.locationDescription = "";
		checkDetails.value.status = null;
		checkDetails.value.remark = "";
		checkDetails.value.imgUrl = '';
		state.imgUrl = [];
	}

	// 新建工单
	const Jump = () => {
		if (isCollapse.value) {
			isCollapse.value = false;
			return;
		}
		uni.navigateTo({
			url: "/pages/Order/addOrder",
		});
	};

	// 是否合格
	const changeRadio = (e) => {
		checkDetails.value.status = e;
	};

	// 获取常见问题列表
	const getProblems = () => {
		getProblemData({
			pageNum: 1,
			pageSize: 1000,
			systemId: state.systemId,
			deviceId: state.deviceId,
			deviceItemId: state.id
		}).then(res => {
			problemList.value = res.rows;
			problemList.value.push({
				id: -1,
				problemContent: '其它'
			})
		})
	}

	// 选择问题
	const changeProblem = (val) => {
		if (val.id == -1) {
			checkDetails.value.problemDescription = '';
		} else {
			checkDetails.value.problemDescription = val.problemContent;
		}
	}

	// 记录详情
	const getDetails = () => {
		// 获取方法
		deviceItem(state.id).then((res) => {
			if (res.code == 200) {
				state.name = res.data.name;
				state.specification = res.data.specification;
			}
		});
	};

	// 记录详情
	const getVideo = () => {
		// 获取视频
		deviceDetail(state.deviceId).then((res) => {
			if (res.code == 200) {
				videoList.value = res.data.referenceVideo ? res.data.referenceVideo.split(',') : []
				videoName.value = res.data.referenceVideoName ? res.data.referenceVideoName.split(',') : []
				checkDetails.value.videoGuidance = res.data.videoGuidance
			}
		});
	};

	// 记录列表
	const getList = () => {
		recordList(queryParams.value).then((res) => {
			if (res.code == 200) {
				let arr = res.rows.map((i, k) => {
					return {
						...i,
						slot: "step" + (k + 1),
						day: timeFormat(Number(new Date(i.createTime)), "mm-dd"),
					};
				});
				dataList.value = queryParams.value.pageNum == 1 ? arr : dataList.value.concat(arr);
				total.value = res.total;
				if (res.total >= dataList.value.length) {
					state.isText = "暂无更多";
				} else {
					state.isText = "点击加载";
				}
			}
		});
	};

	// 切换模块
	const changeTab = (e) => {
		if (e.id == 1) {
			queryParams.value.pageNum = 1;
			getList();
		} else if (e.id == 2) {
			getVideo();
		}
	};

	// 选择视频
	const changeVideo = (e) => {
		state.currentVideo = e
	};

	// 加载更多
	const goMore = () => {
		if (total.value == dataList.value.length) return;
		page.value++;
		getList();
	};
</script>
<style lang="scss" scoped>
	@import "@/uni.scss";

	.more {
		text-align: center;
	}

	.page {
		padding: 30rpx;
	}

	.videoGuidanceSty {
		text-align: left;
		font-size: 28rpx;
		margin-left: 10rpx;
	}


	.tabBox {
		display: flex;
		justify-content: space-between;
		width: 100%;
		padding: 10rpx 20rpx 0;
		box-sizing: border-box;
		text-align: left;
		font-size: 30rpx;
		overflow-x: auto;

		.tab_list {
			min-width: 80rpx;
			padding: 10rpx 20rpx;
			margin-right: 20rpx;
			border-radius: 10rpx;
			text-align: center !important;
		}
	}

	.step-remark {
		position: absolute;
		left: 50rpx;
		top: 60rpx;
		background: #fff;
		border-radius: 20rpx;
		border: 2rpx solid #dedede;
		box-sizing: border-box;
		width: 580rpx;
		height: 260rpx;

		.step-row {
			display: flex;
			justify-content: space-between;

			&-left {
				max-width: 410rpx;
				flex: 1;
				padding: 20rpx 0 20rpx 20rpx;
				padding-bottom: 0;

				.operator {
					font-size: 36rpx;
					color: #212121;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.post-tag {
					min-width: 220rpx;
					font-size: 24rpx;
					color: #757575;
					margin-left: 30rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.step {
					color: #4ea770;
					font-size: 24rpx;
					margin-top: 20rpx;
					display: inline-block;
					padding: 6rpx 20rpx;
					background: #e6f1e9;
					border-radius: 8rpx;
					border: 2rpx solid #abd49d;
				}

				.red {
					color: #eb736c;
					background: #fbeeee;
					border: 1px solid #e3a0a0;
				}
			}
		}

		.step-bottom {
			padding: 20rpx;
			padding-top: 0;
		}
	}

	.add-icon {
		width: 174rpx;
		position: fixed;
		bottom: 104rpx;
		height: 70rpx;
		z-index: 100;
		transition: all 0.5s;
		box-shadow: 0 0 30rpx 2rpx rgba(0, 0, 0, 0.16);
		border-radius: 12rpx 0 0 12rpx;
	}

	.list {
		width: 100%;

		.req {
			max-height: 340rpx;
			overflow-y: auto;
		}

		.list_tit {
			border-bottom: 2rpx solid gainsboro;
		}

		.des {
			width: 140rpx;
			text-align: center;
		}

		.radioBox {
			border: 2rpx soild goldenrod;
			width: 160rpx;
			height: 100rpx;
		}
	}
	
	.btn-box {
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;
		border-top: 1px solid #f5f5f5;
		margin-top: 20rpx;
		z-index: 9;
	}
	:deep() {
		.uv-radio {
			border: 2rpx solid #dcdfe6;
			padding: 20rpx 40rpx;
			border-radius: 10rpx;
			margin: 20rpx 80rpx;
			margin-right: 20rpx;
		}
	}
</style>